/* setscokopt.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
// 缓冲区大小
#define N 64
typedef struct sockaddr SA;
void handler(int signo)
{
    printf("interrupted by SIGALRM\n");
}

int main(void)
{
    int sockfd;
    char buf[N];
    struct sockaddr_in servaddr;
    struct sigaction act;
    if((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("fail to socket");
        exit(-1);
    }
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = PF_INET;
    servaddr.sin_port = htons(9999);
    servaddr.sin_addr.s_addr = inet_addr("192.168.1.100");
    if (bind(sockfd, (SA *)&servaddr, sizeof(servaddr)) < 0)
    {
        perror("fail to bind");
        exit(-1);
    }
    sigaction(SIGALRM, NULL, &act);
    // 指定信号处理函数
    act.sa_handler = handler;
    // 清除SA_RESTART标志位
    sigaction(SIGALRM, &act, NULL);
    alarm(6);

    if (recvfrom(sockfd, buf, N, 0, NULL, NULL) <0 )
    {
        perror("fail to recvfrom");
        exit(-1);
    }
    printf("recv data :%s \n", buf);
    // 取消定时器
    alarm(0);
    return 0;
}